package main

import (
	"fmt"
	"strconv"
	"strings"
)

// ConvertToBytesUnit 将给定的值从KB、MB或GB转换为字节
//
//	// 示例：将1GB转换为字节
//	bytes, err := ConvertToBytes(1, "GB")
//	if err != nil {
//		fmt.Println("Error:", err)
//	} else {
//		fmt.Printf("1GB is equal to %d bytes\n", bytes)
//
//	}
//
//	// 示例：将500MB转换为字节
//	bytes, err = ConvertToBytes(500, "MB")
//	if err != nil {
//		fmt.Println("Error:", err)
//	} else {
//
//		fmt.Printf("500MB is equal to %d bytes\n", bytes)
//	}
//
//	// 示例：将10KB转换为字节
//	bytes, err = ConvertToBytes(10, "KB")
//	if err != nil {
//		fmt.Println("Error:", err)
//	} else {
//		fmt.Printf("10KB is equal to %d bytes\n", bytes)
//	}
func ConvertToBytesUnit(value float64, unit string) (int64, error) {
	var multiplier float64
	switch strings.ToLower(unit) {
	case "kb":
		multiplier = 1024
	case "mb":
		multiplier = 1024 * 1024
	case "gb":
		multiplier = 1024 * 1024 * 1024
	case "tb":
		multiplier = 1024 * 1024 * 1024 * 1024
	case "pb":
		multiplier = 1024 * 1024 * 1024 * 1024 * 1024
	case "eb":
		multiplier = 1024 * 1024 * 1024 * 1024 * 1024 * 1024
	default:
		return 0, fmt.Errorf("unsupported unit: %s", unit)
	}
	return int64(value * multiplier), nil
}

func ConvertToByte(in string) (int64, error) {
	in = strings.ToLower(in)
	in = strings.TrimSpace(in)
	var multiplier float64
	var unit string
	var err error
	switch {
	case strings.HasSuffix(in, "kb"), strings.HasSuffix(in, "mb"), strings.HasSuffix(in, "gb"), strings.HasSuffix(in, "tb"), strings.HasSuffix(in, "pb"), strings.HasSuffix(in, "eb"):
		k := strings.Index(in, "kb")
		k = len(in) - 2
		multiplier, err = strconv.ParseFloat(strings.TrimSpace(in[:k]), 64)
		if err != nil {
			return 0, fmt.Errorf("failed to convert %v to float: %s", in[:k], err)
		}
		unit = in[k:]
	default:
		multiplier, err = strconv.ParseFloat(strings.TrimSpace(in), 64)
		if err != nil {
			return 0, fmt.Errorf("failed to convert %v to float64: %s", in, err)
		}
		return int64(multiplier), nil
	}
	return ConvertToBytesUnit(multiplier, unit)
}
